﻿using streamsearcher;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;


namespace FileSearcher
{
    public class fileSearcher
    {
        private readonly StreamSearcher _searcher;
        private const int BufferSize = 16;

        public fileSearcher(byte[] patternBytes)
        {
            _searcher = new StreamSearcher(patternBytes);
        }

        public void SearchInFile(string fileName)
        {

            using (var stream = File.Open(fileName, FileMode.Open, FileAccess.Read))
            {
                long absoluted_start;
                long absoluted_end;
                absoluted_start = absoluted_end = stream.Position; //开始都指向文件流的起始位置

                using (var sr = new BinaryReader(stream))
                {

                    while (sr.BaseStream.Position + _searcher.PatternLength < sr.BaseStream.Length)//是否读到最后一帧
                    {
                        try
                        {
                            byte[] data = sr.ReadBytes(BufferSize);

                            var ms = new MemoryStream(data);
                            while (ms.Position < ms.Length)
                            {
                                long position = _searcher.Search(ms);

                                if (position == -1)
                                {
                                    stream.Seek(stream.Position - (_searcher.PatternLength - 1), SeekOrigin.Begin); //回退到前一帧不超过模式串长度位置  
                                    break;
                                }
                                else
                                {

                                    absoluted_end = stream.Position - (ms.Length - ms.Position);//确定该帧在原文件流对应绝对位置
                                    Console.WriteLine($"New Frame-absolute start: {absoluted_start}, absolute end: {absoluted_end}");

                                    absoluted_start = absoluted_end + 1;
                                }
                            }
                        }
                        catch (EndOfStreamException ex)

                        {
                            Console.WriteLine("Done!");
                            break;
                        }

                    }
                }

            }
        }

    }
}